package cn.edu.pku.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.edu.pku.constant.EnumStatus;
import cn.edu.pku.entity.BookInfo;
import cn.edu.pku.entity.BorrowInfo;
import cn.edu.pku.mapper.BookInfoMapper;
import cn.edu.pku.mapper.BorrowInfoMapper;
import cn.edu.pku.vo.BorrowInfoResponse;
import cn.edu.pku.vo.request.BorrowInfoRequest;

@Service
public class BorrowInfoService {

	@Autowired
	BorrowInfoMapper borrowInfoMapper;
	
	@Autowired
	BookInfoMapper bookInfoMapper;
	
	public PageInfo<BorrowInfoResponse> getBorrowInfoList(Integer pageNum,Integer pageSize,BorrowInfoRequest borrowInfoRequest){
		PageHelper.startPage(pageNum, pageSize);
		List<BorrowInfoResponse> borrowInfoList = borrowInfoMapper.getBorrowInfoList(borrowInfoRequest);
		PageInfo<BorrowInfoResponse> pageInfo=new PageInfo<>(borrowInfoList);
		return pageInfo;
	}
	public BorrowInfo getBorrowInfoById(Integer id){
		return borrowInfoMapper.selectByPrimaryKey(id);
	}
	
	public int updateBorrowInfo(Integer id){
		 BorrowInfo record=this.getBorrowInfoById(id);
		 record.setStatus(EnumStatus.RETURN_BOOK.getStatus().byteValue());//
		 record.setReturnTime(new Date());
		 return borrowInfoMapper.updateByPrimaryKey(record);
	}
	
	public int returnBook(Integer id){
		BorrowInfo borrowInfoById = this.getBorrowInfoById(id);
		BookInfo bookInfo=bookInfoMapper.selectByPrimaryKey(borrowInfoById.getBookId());
		bookInfo.setStatus(EnumStatus.RETURN_BOOK.getStatus().byteValue());
		bookInfo.setuTime(new Date());
		int updateByPrimaryKeySelective = bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
		if (updateByPrimaryKeySelective>0) {
			return this.updateBorrowInfo(id);
		} else {
			return -1;
		}
	}
	
	public int borrowerBook(Integer borrowerId,Integer bookId){
		return 1;
	}
	
	
}
